<template>
  <view class="common profile pos-r">
    <view class="pos-a z-0 wp-100" :class="env === 'H5' ? 'bg-yel' : 'bg-lg'" :style="globalData.barStyle" />
    <u-navbar :fixed="false">
      <u-icon slot="left" name="arrow-left" :color="env === 'H5' ? '#fff' : '#000'" size="19" @tap="navigateBack" />
      <view slot="center" :class="[env === 'H5' ? 'c-fff' : 'c-bla']">个人资料</view>
    </u-navbar>
    <view class="main bg-gry">
      <view class="bg-whi">
        <u-cell-group>
          <u-cell title="实名认证">
            <template #right-icon>
              <!-- #ifndef H5 -->
              <u-image width="40rpx" height="40rpx" @tap="chooseImage" shape="circle" :src="userInfo.avatarUrl || '/static/images/my/avatar.png'" class="br-f" mode="aspectFill" />
              <!-- #endif -->
              <!-- #ifdef H5 -->
              <el-upload
                ref="upload"
                class="upload-demo"
                action="#"
                :http-request="handleUpload"
                :before-upload="beforeUpload"
                :show-file-list="false"
                accept="image/*"
                :file-list="fileList"
                :on-change="changeUploadFile"
                :auto-upload="true"
              >
                <u-image width="40rpx" height="40rpx" shape="circle" :src="userInfo.avatarUrl || '/static/images/my/avatar.png'" class="br-f" mode="aspectFill" />
              </el-upload>
              <!-- #endif -->
            </template>
          </u-cell>
          <u-cell title="昵称" @click="gotoChangeNickname" :value="userInfo.nickName" isLink url="/pages/my/changeNickname" />
          <u-cell title="手机号" @click="gotoChangePhone" :value="userInfo.phoneNumber" isLink url="/pages/my/changePhone" />
          <u-cell title="设置" @click="gotoSetting" isLink url="/pages/my/setting" />
        </u-cell-group>
      </view>
    </view>
  </view>
</template>

<script>
import commonMxins from '@/mixins/common.js';
export default {
  mixins: [commonMxins],
  data() {
    return {
      userInfo: {
        avatarUrl: '',
        nickName: '',
        phoneNumber: ''
      },
      tempAvatar: '',
      headers: { 'content-type': 'multipart/form-data', Authorization: uni.getStorageSync('ACCESS_TOKEN') },
      // 导入上传文件的参数
      fileList: [], //导入的文件
      isSelectedFile: false, //是否选中文件
      fileSizeMB: 0 //上传的文件尺寸
    };
  },
  onLoad() {
    this.initData();

    // 接收从更改昵称页面返回的更新信息
    const eventChannel = this.getOpenerEventChannel();
    if (eventChannel) {
      eventChannel.on('nicknameUpdated', data => {
        if (data && data.nickname) {
          this.userInfo.nickName = data.nickname;
          // 更新本地存储
          this.updateLocalUserInfo();
        }
      });
    }
  },
  onShow() {
    // 每次显示页面时重新加载用户信息
    this.initData();
  },
  methods: {
    async initData() {
      const storedUserInfo = uni.getStorageSync('userInfo');
      if (storedUserInfo) {
        const userInfo = typeof storedUserInfo === 'string' ? JSON.parse(storedUserInfo) : storedUserInfo;
        this.userInfo = { ...this.userInfo, ...userInfo };
        this.tempAvatar = this.userInfo.avatarUrl;
      }
    },

    // 格式化手机号
    formatPhone(phone) {
      if (!phone) return '';
      return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
    },

    //选择头像--APP
    chooseImage() {
      uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图
        sourceType: ['album'], // 可以指定来源是相册还是相机
        extension: ['jpg', 'jpeg', 'png'], // 指定是图片
        success: async resp => {
          let res = await this.$uploadFile({ url: '/app/upload/uploadFile', filePath: resp.tempFilePaths[0] });
          this.userInfo.avatarUrl = res.data.url;
        },
        fail: function (err) {
          uni.hideLoading();
          console.log(err);
        }
      });
    },
    //上传头像--H5
    async handleUpload(option) {
      const file = option.file;
      const formData = new FormData();
      formData.append('file', file);
      let res = await this.$uploadFile({ url: '/app/upload/uploadFile', filePath: formData });
      if (res.code === 200 && res.data) {
        this.userInfo.avatarUrl = res.data.url;
        await this.$request({ url: '/app/appUser/updateAvatar', method: 'POST', data: { avatarUrl: this.userInfo.avatarUrl } });
        uni.setStorageSync('userInfo', this.userInfo);
        this.$u.toast('图片上传成功');
      } else {
        this.$u.toast('图片上传失败');
      }
    },
    // 上传前验证
    beforeUpload(file) {
      const isImage = file.type.indexOf('image/') === 0;
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isImage) {
        this.$u.toast('请输入正确的手机号');
        return false;
      }
      if (!isLt2M) {
        this.$u.toast('上传图片大小不能超过 2MB!');
        return false;
      }
      return true;
    },
    // 文件状态改变触发此方法
    changeUploadFile(file, fileList) {
      this.fileList = fileList;
      const fileSize = file.size; // 单位：字节 (Bytes)
      const fileSizeKB = Math.round(fileSize / 1024); // 转 KB
      const fileSizeMB = (fileSizeKB / 1024).toFixed(2); // 转 MB
      this.fileSizeMB = fileSizeMB;
      this.isSelectedFile = true;
    },
    // 跳转到更改昵称页面
    gotoChangeNickname() {
      uni.navigateTo({
        url: '/pages/my/profile/changeNickname',
        success: res => {
          // 传递当前昵称
          res.eventChannel.emit('currentNickname', {
            nickname: this.userInfo.nickName
          });
        }
      });
    },

    // 跳转到更换手机号页面
    gotoChangePhone() {
      uni.navigateTo({
        url: '/pages/my/changePhone'
      });
    },
    
    // 跳转到设置页面
    gotoSetting() {
      uni.navigateTo({
        url: '/pages/my/setting'
      });
    },

    // 更新本地存储的用户信息
    updateLocalUserInfo() {
      try {
        uni.setStorageSync('userInfo', this.userInfo);
      } catch (error) {
        console.error('更新本地用户信息失败:', error);
      }
    }
  }
};
</script>
